package com.kcs.fxmargin.service;

import java.sql.Connection;
import java.sql.PreparedStatement;
import java.sql.ResultSet;
import java.util.ArrayList;
import java.util.List;

import com.kcs.common.utils.ConnectionUtils;
import com.kcs.common.utils.Constant;
import com.kcs.fxmargin.dao.CommonDao;
import com.kcs.fxmargin.model.CConfigSys;
import com.kcs.fxmargin.model.MCurrency;

public class CommonService {
	CommonDao dao = new CommonDao();
	
	public int getRowVersion(String tableName, String id) throws Exception {
		
		Connection conn 			= null;
		PreparedStatement pstm 		= null;
		ResultSet rs				= null;
		int rowVersion 				= 0;
		
		try{
			conn = ConnectionUtils.getConnection(Constant.MSSQL, Constant.TO); // get connection fxmargin from mssql
			rowVersion = dao.getRowVersion(conn, pstm, rs, tableName, id);
			
		} catch (Exception e){
			throw e;
		} finally {
			if(conn != null ) conn.close();
			if(pstm != null ) pstm.close();
			if(rs   != null ) rs.close();
		}
		
		return rowVersion;
	}

	public List<MCurrency> getCurrencyList() throws Exception {
		Connection conn 				= null;
		PreparedStatement pstm 			= null;
		ResultSet rs					= null;
		List<MCurrency> currencyList 	= new ArrayList<MCurrency>();
		
		try{
			conn = ConnectionUtils.getConnection(Constant.MSSQL, Constant.TO); // get connection fxmargin from mssql
			currencyList = dao.getCurrencyList(conn, pstm, rs);
			
		} catch (Exception e){
			throw e;
		} finally {
			if(conn != null ) conn.close();
			if(pstm != null ) pstm.close();
			if(rs   != null ) rs.close();
		}
		
		return currencyList;		
	}
	
	public List<CConfigSys> getConfig() throws Exception {
		Connection conn 				= null;
		PreparedStatement pstm 			= null;
		ResultSet rs					= null;
		List<CConfigSys> configList		= new ArrayList<CConfigSys>();
		
		try{
			conn = ConnectionUtils.getConnection(Constant.MSSQL, Constant.TO); // get connection fxmargin from mssql
			configList = dao.getConfig(conn, pstm, rs);
			
		} catch (Exception e){
			
			throw e;
		} finally {
			if(conn != null ) conn.close();
			if(pstm != null ) pstm.close();
			if(rs   != null ) rs.close();
		}
		
		return configList;
	}
	
	public void updateConfig(List<CConfigSys> configList) throws Exception {
		Connection conn 				= null;
		PreparedStatement pstm 			= null;
		
		try {
			conn = ConnectionUtils.getConnection(Constant.MSSQL, Constant.TO); // get connection fxmargin from mssql
			
			for(CConfigSys config : configList) {
				dao.updateConfig(conn, pstm, config);
			}
			
			conn.commit();
			
		} catch (Exception e) {
			conn.rollback();
			throw e;
		} finally {
			if(conn != null ) conn.close();
			if(pstm != null ) pstm.close();
		}
	}
}
